/**
 * Package:com.afteryuan.server.hanlder.core;
 * $Id$
 * Copyright(c) 2001-2005 www.afteryuan.com
 */
package com.afteryuan.server.handler.core;

import com.afteryuan.server.handler.Handler;
import com.afteryuan.server.command.up.CommandUp;
import com.afteryuan.server.command.up.core.LoginUp;
import com.afteryuan.server.command.down.core.PolicyDown;
import com.afteryuan.server.command.down.core.LoginDown;
import com.afteryuan.server.ConnectSession;
import com.afteryuan.server.data.SpritePool;
import com.afteryuan.server.data.Sprite;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.logging.Log;

/**
 * JoinRoomHandler 处理加入Room的请求
 * <p/>
 * 处理步骤:
 * 1.查看该avatar是否已经存在一个在线的sprite,如果已经存在,则通知客户端让其下线,并清除掉此sprite
 * 2.查看是否该avatar是否存在一个游离的sprite,如果存在,则将其激活.(异常断线后会出现此情况)
 * 3.如果都不存在,则新建一个Sprite对象,并放入在线精灵列表
 * 4.发送LoginDown的指令给客户端
 * 5.保存spriteId到ConnectSession
 * <p><a href="PingHandler.java.html"><i>View Source</i></a></p>
 *
 * @author <a href="mailto:afteryuan@afteryuan.com">$Author$</a>
 * @version $Revision$
 */
public class LoginHandler implements Handler {
    private static Log log = LogFactory.getLog(LoginHandler.class);
    private SpritePool spritePool;

    public void setSpritePool(SpritePool spritePool) {
        this.spritePool = spritePool;
    }

    public void process(ConnectSession session, CommandUp command) {
        LoginUp cmd = (LoginUp) command;

        log.debug("do JoinRoom");
        //todo 1.查看该avatar是否已经存在一个激活的sprite,如果已经存在,则通知其下线
        //todo 2.查看是否该avatar是否存在一个游离的sprite,如果存在,则将其激活.
        //3.如果都不存在,则新建一个Sprite对象,并放入在线精灵列表
        Sprite sprite = new Sprite();
        sprite.setId(cmd.sender);
        sprite.setConnectSession(session);
        spritePool.addToServer(sprite);
        //4.发送LoginDown的指令给客户端
        LoginDown down = new LoginDown();
        session.write(down);
        session.setAttribute(Sprite.KEY_SPRITE_ID,sprite);
    }
}